package com.hxalex.simulationhandle.util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

/**
 * 这是一个加载网络图片设置圆角的类
 * 只有顶部左右2个角是圆角
 */
public class GlideRoundTransformv3 extends BitmapTransformation {
    private float radius = 0f;
    private int mDirection = 1;  //1 top  2 bottom
    public float[] mRadiusArray = null;
    private Path mPath = new Path();

    public GlideRoundTransformv3(Context context) {
        this(context, 4);
    }

    public GlideRoundTransformv3(Context context, int dp) {
        this(context, 4, 1);
    }

    public GlideRoundTransformv3(Context context, int dp, int direction) {
        super(context);
        this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
        mDirection = direction;
        if (direction == 2) {
            mRadiusArray = new float[]{
                    0, 0,
                    0, 0,
                    radius, radius,
                    radius, radius};
        } else {
            mRadiusArray = new float[]{
                    radius, radius,
                    radius, radius,
                    0, 0,
                    0, 0};
        }
    }

    @Override
    public Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return roundCrop(pool, toTransform);
    }

    private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;
        RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
        mPath.reset();
        mPath.addRoundRect(rectF, mRadiusArray, Path.Direction.CW);
        mPath.close();
        Bitmap result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();// 定义画笔
        paint.setAntiAlias(true);// 设置抗锯齿
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawPath(mPath, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint);
        return result;
    }

    @Override
    public String getId() {
        return getClass().getName() + Math.round(radius);
    }
}